package com.xingchen.feima.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingchen.feima.common.log.annatation.Log;
import com.xingchen.feima.common.log.enums.BusinessType;
import com.xingchen.feima.common.utils.R;
import com.xingchen.feima.system.entity.Menu;
import com.xingchen.feima.system.entity.Role;
import com.xingchen.feima.system.entity.RoleMenu;
import com.xingchen.feima.system.entity.UserRole;
import com.xingchen.feima.system.entity.vo.RoleSearchConditionObj;
import com.xingchen.feima.system.service.MenuService;
import com.xingchen.feima.system.service.RoleMenuService;
import com.xingchen.feima.system.service.RoleService;
import com.xingchen.feima.system.utils.MenuHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "角色管理")
@RestController
@RequestMapping("/system/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleMenuService roleMenuService;


    @ApiOperation(value = "获取角色列表")
    @GetMapping("")
    public R getList(){
        List<Role> list = roleService.list(null);
        return R.ok().data("items", list);
    }

//    @PreAuthorize("hasAuthority('btn.role.list')")
    @ApiOperation(value = "获取分页角色列表")
    @GetMapping("/{currentPage}/{pageSize}")
    public R getPageList(
            @ApiParam(name = "currentPage", value = "当前页码", required = true)
            @PathVariable Long currentPage,

            @ApiParam(name = "pageSize", value = "每页记录数", required = true)
            @PathVariable Long pageSize){

        Page<Role> pageObj = new Page<>(currentPage, pageSize);
        roleService.page(pageObj, null);

        return  R.ok().data("items", pageObj);
    }

    @ApiOperation(value = "获取条件分页角色列表")
    @PostMapping("/{currentPage}/{pageSize}")
    public R getCondPageList(
            @ApiParam(name = "currentPage", value = "当前页码", required = true)
            @PathVariable Long currentPage,

            @ApiParam(name = "pageSize", value = "每页记录数", required = true)
            @PathVariable Long pageSize,

            @ApiParam(name = "searchConditionObj", value = "搜索条件", required = false)
            @RequestBody RoleSearchConditionObj searchConditionObj){

        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();

        String name = searchConditionObj.getRoleName();

        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("plant_name", name);
        }

        Page<Role> pageObj = new Page<>(currentPage, pageSize);
        roleService.page(pageObj, queryWrapper);

        return  R.ok().data("items", pageObj);
    }

    @Log(title = "角色管理", businessType = BusinessType.INSERT)
//    @PreAuthorize("hasAuthority('btn.role.add')")
    @ApiOperation(value = "新增角色")
    @PostMapping("")
    public R add(
            @ApiParam(name = "plant", value = "角色对象", required = true)
            @RequestBody Role plant){

        roleService.save(plant);
        return R.ok();
    }

    @ApiOperation(value = "根据ID查询角色")
    @GetMapping("/{id}")
    public R getById(
            @ApiParam(name = "id", value = "角色ID", required = true)
            @PathVariable Long id){

        Role plant = roleService.getById(id);
        return R.ok().data("items", plant);
    }

    @ApiOperation(value = "根据ID修改角色")
    @PutMapping("")
    public R updateById(
            @ApiParam(name = "plant", value = "角色对象", required = true)
            @RequestBody Role plant){

        roleService.updateById(plant);
        return R.ok();
    }

    @ApiOperation(value = "根据ID删除角色")
    @DeleteMapping("/{id}")
    public R removeById(
            @ApiParam(name = "id", value = "角色ID", required = true)
            @PathVariable Long id){

        roleService.removeById(id);
        return R.ok();
    }

    @ApiOperation("根据ID列表批量删除角色")
    @DeleteMapping("/batchRemove")
    public R batchRemove(
            @ApiParam(name = "idList", value = "ID列表", required = true)
            @RequestBody List<Long> idList) {

        roleService.removeByIds(idList);
        return R.ok();
    }

    @ApiOperation(value = "展示角色菜单:需要获取所有菜单和当前角色的菜单")
    @GetMapping("/showMenu/{roleId}")
    public R showMenu(
            @ApiParam(name = "roleId", value = "角色ID", required = true)
            @PathVariable Long roleId) {
        // 获取所有status为1的菜单列表
        List<Menu> menuList = menuService.list(new QueryWrapper<Menu>().eq("status", 1).orderByAsc("sort_value"));
        // 根据角色id获取角色菜单对象列表
        List<RoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<RoleMenu>().eq("role_id", roleId));
        // 获取该角色已分配的所有菜单id
        List<Long> menuIdListForCurrentRole = roleMenuList.stream().map(roleMenu -> roleMenu.getMenuId()).collect(Collectors.toList());
        // 遍历所有菜单，如果该角色已分配该菜单，将该菜单的select属性设置为true
        menuList.forEach(menu -> menu.setSelect(menuIdListForCurrentRole.contains(menu.getId())));
        //将菜单列表转换为菜单树
        List<Menu> sysMenus = MenuHelper.buildTree(menuList);

        return R.ok().data("items", sysMenus);
    }

    @ApiOperation(value = "给角色分配菜单")
    @PostMapping("/assignMenu/{roleId}")
    public R assignMenu(
            @ApiParam(name = "roleId", value = "角色ID", required = true)
            @PathVariable Long roleId,

            @ApiParam(name = "alreadyAssignMenuIdList", value = "已分配菜单id列表", required = true)
            @RequestBody List<Long> alreadyAssignMenuIdList) {

        // 删除当前角色已分配的权限
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("role_id", roleId));
        // 根据已分配角色id列表生成用户角色对象列表，然后进行批量保存
        List<RoleMenu> userRoleList = alreadyAssignMenuIdList.stream().map(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);
            return roleMenu;
        }).collect(Collectors.toList());
        roleMenuService.saveBatch(userRoleList);

        return R.ok();
    }

}




















